const MongoClient = require('mongodb').MongoClient

var clientMap = {}

async function getClient (url) {
  var client = clientMap[url]

  if (!client) {
    client = await MongoClient.connect(url)
    clientMap[url] = client
  }

  return client
}

module.exports = function (app) {
  app.get('/databases', async function (req, res) {
    try {
      const query = req.query
      const url = `mongodb://${query.hostname}:${query.port}`

      const client = await getClient(url)

      const db = client.db()
      const adminDb = db.admin()

      var dbs = await adminDb.listDatabases()
      var totalSize = dbs.totalSize

      dbs = dbs.databases.map(database => client.db(database.name))

      var databases = await Promise.all(dbs.map(async (d) => {
        var stats = await d.stats()
        return stats
      }))

      res.json({
        totalSize: totalSize,
        databases: databases
      })
    } catch (error) {
      res.status(500).json({ error: error.message })
    }
  })

  app.get('/databases/:dbName', async function (req, res) {
    try {
      const dbName = req.params.dbName
      const query = req.query
      const needStats = query.stats === 'true'

      const url = `mongodb://${query.hostname}:${query.port}`

      const client = await getClient(url)
      const db = client.db(dbName)

      const collections = await db.collections()

      const result = await Promise.all(collections.map(async (collection) => {
        var stats = null

        if (needStats) {
          stats = await collection.stats()
        }

        return {
          collectionName: collection.collectionName,
          dbName: collection.dbName,
          hint: collection.hit,
          namespace: collection.namespace,
          stats: stats
        }
      }))

      res.json(result)
    } catch (error) {
      res.status(500).json({ error: error.message })
    }
  })

  app.get('/databases/:dbName/:colName', async function (req, res) {
    try {
      const dbName = req.params.dbName
      const colName = req.params.colName
      const query = req.query

      const url = `mongodb://${query.hostname}:${query.port}`

      const client = await getClient(url)
      const col = client.db(dbName).collection(colName)
      
      var items =await col.find({}).toArray()
      res.json(items)
    }
    catch (error) {
      res.status(500).json({ error: error.message })
    }
  })
}
